package com.game.boxman;

public class GameMap {
    private static final char WALL = '#';
    private static final char FLOOR = ' ';
    private static final char PLAYER = 'P';
    private static final char BOX = 'B';
    private static final char TARGET = 'T';

    private final char[][] map;
    private final int rows;
    private final int cols;

    public GameMap() {
        String[] level = {
            "#####",
            "##  #",
            "#P B ",
            "#  T ",
            "#    ",
            "#####"
        };

        this.rows = level.length;
        this.cols = level[0].length();
        this.map = new char[rows][cols];

        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < cols; x++) {
                map[y][x] = level[y].charAt(x);
            }
        }
    }

    public int getRows() {
        return rows;
    }

    public int getCols() {
        return cols;
    }

    public int getPlayerX() {
        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < cols; x++) {
                if (map[y][x] == PLAYER) {
                    return x;
                }
            }
        }
        return -1;
    }

    public int getPlayerY() {
        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < cols; x++) {
                if (map[y][x] == PLAYER) {
                    return y;
                }
            }
        }
        return -1;
    }

    public boolean isWall(int x, int y) {
        return map[y][x] == WALL;
    }

    public boolean isFloor(int x, int y) {
        return map[y][x] == FLOOR;
    }

    public boolean isTarget(int x, int y) {
        return map[y][x] == TARGET;
    }

    public boolean isBox(int x, int y) {
        return map[y][x] == BOX;
    }

    public boolean isMoveValid(int playerX, int playerY, int newX, int newY) {
        return !isWall(newX, newY) && (isFloor(newX, newY) || isBox(newX, newY));
    }

    public void moveBox(int boxX, int boxY, int newX, int newY) {
        map[boxY][boxX] = FLOOR;
        map[newY][newX] = BOX;
    }

    public boolean isAllBoxesOnTargets() {
        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < cols; x++) {
                if (map[y][x] == BOX && !isTarget(x, y)) {
                    return false;
                }
            }
        }
        return true;
    }
}